<template>
  <div>
    <el-card class="elCard" style="height: 80px">
      <el-form label-width="80px" :inline="true" >
        <el-form-item label="菜单名称">
          <el-input v-model="searchParam.menuName" style="width: 240px" placeholder="请输入菜单名称"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchParam.status" style="width: 240px" clearable>
            <el-option
                v-for="menuStatus in [{lable:'正常',value:'0'},{lable:'停用',value:'1'}]"
                :label="menuStatus.lable"
                :value="menuStatus.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchMenuList">搜索</el-button>
          <el-button @click="resetSearchParam">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="elCard">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="info">展开折叠</el-button>
      <el-table
          :data="menuList"
          row-key="menuId"
      >
        <el-table-column label="菜单名称" prop="menuName" align="center" width="200px"/>
        <el-table-column label="图标" prop="icon" align="center"/>
        <el-table-column label="排序" prop="orderNum" align="center"/>
        <el-table-column label="权限标识" prop="perms" align="center"/>
        <el-table-column label="组件路径" prop="component" align="center"/>
        <el-table-column label="状态" prop="status" align="center"/>
        <el-table-column label="创建时间" prop="createTime" align="center" width="200px"/>
        <el-table-column label="操作" align="center" width="250px">
          <template #default="scope">
            <el-button type="primary" @click="handleUpdate(scope.row.menuId)">修改</el-button>
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="handleDeleteMenu(scope.row.menuId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="showMenuDialog" :title="menuDialogTitle" width="700px">
      <el-form label-width="80px" class="menu-form" :model="menuForm" :rules="rules" ref="menuFormRef">
        <el-row>
          <el-col :span="24">
            <!--            check-strictly=true 时，任何节点都可以被选择，否则只有子节点可被选择-->
            <el-form-item label="上级菜单">
              <el-tree-select
                  v-model="menuForm.parentId"
                  :data="menuList"
                  check-strictly
                  :props="{label:'menuName'}"
                  node-key="menuId"
                  clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单类型">
              <el-radio-group v-model="menuForm.menuType">
                <el-radio value="M">目录</el-radio>
                <el-radio value="C">菜单</el-radio>
                <el-radio value="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="menuForm.menuName" placeholder="请输入菜单名称" class="form-content"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="menuForm.orderNum" class="form-content"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否外链">
              <el-radio-group v-model="menuForm.isFrame">
                <el-radio value="0">是</el-radio>
                <el-radio value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="menuForm.path" placeholder="请输入路由地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="menuForm.visible">
                <el-radio value="0">显示</el-radio>
                <el-radio value="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态">
              <el-radio-group v-model="menuForm.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="showMenuDialog=false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdateMenu">确定</el-button>
      </template>
    </el-dialog>
  </div>

</template>
<script setup>
import {
  ElCard,
  ElInput,
  ElButton,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElRow,
  ElCol,
  ElRadioGroup,
  ElRadio,
  ElInputNumber,
  ElTreeSelect, ElMessage, ElMenu
} from "element-plus"
import {getMenuList, saveMenu, updateMenu, getMenuDetail, deleteMenu} from "@/api/menu/menu.js";
import {nextTick, onMounted, reactive, ref} from "vue";
import {handleTree} from "@/utils/common.js";


let searchParam=ref()
let resetSearchParam=()=>{
    searchParam.value={
      menuName:null,
      status:null
    }
}
resetSearchParam()

let menuList = ref([])
const fetchMenuList = async () => {
  getMenuList(searchParam.value).then(resp => {
    if (resp.code === 200) {
      menuList.value = handleTree(resp.data, "menuId")
      console.log(menuList, 5555)
    }
  })
}

onMounted(() => {
  fetchMenuList()
})

let showMenuDialog = ref(false)
let menuDialogTitle = ref("")
let menuForm = ref({})

let resetMenuForm = () => {
  menuForm.value = {
    "parentId": null,
    "menuName": "",
    "icon": "",
    "menuType": "M",//类型（M目录 C菜单 F按钮）
    "orderNum": null,
    "isFrame": "1",//是否为外链（0是 1否）
    "visible": "0",// 显示状态（0显示 1隐藏）
    "status": "0",//菜单状态（0正常 1停用）
    "path": ""
  }
}
onMounted(() => {
  resetMenuForm()
})

let menuNameValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error("菜单名称不能为空"))
  } else {
    callback()
  }

}

let pathValidator = (rule, value, callback) => {
  if (value) {
    callback()
  } else {
    callback(new Error("路由地址不能为空"))
  }
}
let rules = ref({
      menuName: [{required: true, trigger: "blur", validator: menuNameValidator}],
      orderNum: [{required: true, trigger: "blur", message: "显示排序不能为空"}],
      path: [{required: true, trigger: "blur", validator: pathValidator}]
    }
)
let handleUpdate = async (menuId) => {
  await fetchMenuList()
  getMenuDetail(menuId).then(resp => {
    if (resp.code === 200) {
      menuForm.value = resp.data
      if (!menuForm.value.parentId) {
        menuForm.value.parentId = null
      }
      showMenuDialog.value = true
      menuDialogTitle = "修改菜单"
      nextTick(() => {
        menuFormRef.value.clearValidate()
      })
    }

  })

}

let menuFormRef = ref()
let handleAdd = async () => {
  resetMenuForm();
  await fetchMenuList()
  showMenuDialog.value = true
  menuDialogTitle = "新增菜单"
  nextTick(() => {
    menuFormRef.value.clearValidate()
  })
}

let saveOrUpdateMenu = async () => {
  menuFormRef.value.validate()
  let resp;
  let menu = menuForm.value;
  let message;
  if (menu.menuId) {
    resp = await updateMenu(menu)
    message = "修改菜单成功"
  } else {
    resp = await saveMenu(menu)
    message = "保存菜单成功"
  }

  if (resp.code === 200) {
    ElMessage.success(message)
    showMenuDialog.value = false
    fetchMenuList()
  }
}

let handleDeleteMenu = (menuId) => {
  deleteMenu(menuId).then(resp => {
    if (resp.code === 200) {
      ElMessage.success("删除成功")
      fetchMenuList()
    }
  })
}
</script>
<style scoped lang="scss">
.elCard {
  margin: 0 30px;
  margin-bottom: 10px;
}

.menu-form {

  .form-content {
    width: 240px;
  }
}
</style>